import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import LoginView from '../views/LoginView.vue'
import AdminLayout from '../components/AdminLayout.vue'
import HomeView from '../views/HomeView.vue'
import AboutView from '../views/AboutView.vue'
import UsersView from '../views/UsersView.vue'
import ProfileView from '../views/ProfileView.vue'
import SettingsView from '../views/SettingsView.vue'
import { getToken } from '@/utils/auth'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'main',
    component: AdminLayout,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '',
        name: 'home',
        component: HomeView
      },
      {
        path: 'about',
        name: 'about',
        component: AboutView
      },
      {
        path: 'profile',
        name: 'profile',
        component: ProfileView
      },
      {
        path: 'users',
        name: 'users',
        component: UsersView
      },
      {
        path: 'settings',
        name: 'settings',
        component: SettingsView
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局前置守卫，处理认证逻辑
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  const requiresAuth = to.meta.requiresAuth || false
  
  // 检查用户是否已登录（通过检查token）
  const isAuthenticated = !!getToken()
  
  // 如果路由需要认证但用户未登录，则重定向到登录页面
  if (requiresAuth && !isAuthenticated) {
    next({
      path: '/login',
      query: { redirect: to.fullPath } // 保存用户想要访问的原始路径，登录后可以重定向回去
    })
  } 
  // 如果用户已登录但尝试访问登录页面，则重定向到首页
  else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } 
  // 其他情况，直接通过
  else {
    next()
  }
})

export default router